<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'mf:fh:mfCarplanFhH:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="70%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" @keyup.enter.native="handleEnterKey">
      <template #posChildList>
        <a-button class="mb-2" @click="handleposChildAdd" v-auth="'mf:fh:mfCarplanFhH:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
        <BasicTable @register="registerposChildTable" @row-click="handleposChildRowClick" @edit-change="rowChange">

          <template #gxListSelect="{ record: childRecord }">
            <ListSelect
              v-model:value="childRecord.cposition"
              :labelValue="childRecord.cposName"
              ref="tjdgxlist"
              selectType="invPositionSumSelect"
              :queryParams="{
                cwhCode:record.cwhcode,
                cinvCode:record.invCode,
                autoid:record.autoid,
              }"
              @select="handSelectgx($event, childRecord)"
            />
          </template>
        </BasicTable>
      </template>
      </BasicForm>

  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsWmsWeighbridgeForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { carVenTreeData } from '/@/api/wms/weighbridge/carVen';
  import { CarplanFh, mfCarplanFhCForm, mfCarplanFhCSave,mfCarplanFhCSaveData } from '/@/api/wms/weighbridge/fh';
  import { BasicTable, useTable } from '/@/components/Table';
  import { ListSelect } from '/@/components/ListSelect';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('sys.dh');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<CarplanFh>({} as CarplanFh);
  const carType = ref<any>('');
  const obj = ref<any>({});

    


  const getTitle = computed(() => ({
    icon: meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增销售发货装车计划详情') : t('编辑销售发货装车计划详情'),
  }));

  const inputFormSchemas: FormSchema[] = [
    // {
    //   label: t('ID'),
    //   field: 'id',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 64,
    //   },
    //   required: true,
    //   ifShow: false,
    // },
    {
      label: t('发货单号'),
      field: 'soCode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      show: false,
    },
    // {
    //   label: t('存货编码'),
    //   field: 'invCode',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 100,
    //   },
    //   show: false,
    // },
    {
      label: t('存货名称'),
      field: 'invName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      show: false,
    },
    {
      label: t('规格型号'),
      field: 'invStd',
      component: 'Input',
      componentProps: {
        maxlength: 200,
      },
      show: false,
    },
    {
      label: t('客户'),
      field: 'cusName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      show: false,
    },
    {
      label: t('合同号'),
      field: 'contractCode',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      show: false,
    },

    {
      label: t('计划发货重量'),
      field: 'planWeight',
      component: 'InputNumber',
      componentProps: {
        maxlength: 100,
        onChange:async(e)=>{
          console.log(e);
          if(carType.value == '1'){
            if(e>0){
              let obj = await getFieldsValue()
              setFieldsValue({
                ...obj,
                planWeight:-e
              })
            }
          }else{
            if(e<0){
              let obj = await getFieldsValue()
              setFieldsValue({
                ...obj,
                planWeight:-e
              })
            }
          }
         
        }
      },
      // dynamicDisabled: true,
      required: true,
    },
    {
      label: t('建议发货重量'),
      field: 'jyWeight',
      component: 'InputNumber',
      componentProps: {
        maxlength: 100,
      },
      show: false,
    },
    {
      label: t('客户重量'),
      field: 'cusWeight',
      component: 'InputNumber',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('出库仓库'),
      field: 'cwhname',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
   
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        // rows: 5,
      },
      dynamicDisabled: true,
    },
    {
      label: t('累计确认重量'),
      field: 'qrWeight',
      component: 'InputNumber',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('货位信息'),
      field: 'posChildList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'posChildList',
    },
    // {
    //   label: t('确认入库重量'),
    //   field: 'qrWeight',
    //   component: 'InputNumber',
    //   componentProps: {
    //     maxlength: 100,
    //     onChange:async(e)=>{
    //       console.log(e);
    //       if(carType.value == '1'){
    //         if(e>0){
    //           let obj = await getFieldsValue()
    //           setFieldsValue({
    //             ...obj,
    //             qrWeight:-e
    //           })
    //         }
    //       }else{
    //         if(e<0){
    //           let obj = await getFieldsValue()
    //           setFieldsValue({
    //             ...obj,
    //             qrWeight:-e
    //           })
    //         }
    //       }
         
    //     }
    //   },
    //   required: true,
    // },
  ];


  async function setposChildTableData(_res: Recordable) {
    posChildTable.setColumns([
      {
        title: t('确认发货重量'),
        dataIndex: 'qrWeight',
        width: 150,
        align: 'left',
        editRow: true,
        editComponent: 'InputNumber',
        // editRule: true,
        editRule: (value, _record) => {
          console.log(value,_record,'=========');
          let iquantity = Number(_record.iquantity) || 0
          let num = Math.abs(value)
          console.log(iquantity,'iquantity=========');
          return new Promise((resolve, reject) => {
            if (!value || value === '') return reject('请输入');

            if (iquantity&& num > iquantity) return reject('数量不能大于' + iquantity);
            return resolve(); // 验证成功
          });
        },
      },
      {
        title: t('发货批次'),
        dataIndex: 'ibatch',
        width: 150,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editRule: true,
      },

      {
        title: t('发货货位'),
        dataIndex: 'cposition',
        width: 130,
        align: 'left',
        slot: 'gxListSelect',
      },
     
      // {
      //   title: t('发货货位'),
      //   dataIndex: 'cposition',
      //   dataLabel: 'cposition',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'ListSelect',
      //   editComponentProps: {
      //     selectType: 'invPositionSumSelect',
      //     onSelect:(value)=>{
      //       obj.value = value[0]
      //       console.log(obj.value,'999999999999');
      //     },
      //     queryParams:{
      //       cwhCode:record.value.cwhcode,
      //       cinvCode:record.value.invCode,
      //       autoid:record.value.autoid,
      //     },
      //     checkbox: false,
      //   },
      //   editRule: false,
      // },
      {
        title: t('件数'),
        dataIndex: 'qty',
        width: 150,
        align: 'left',
        editRow: true,
        editComponent: 'InputNumber',
      },
      {
        title: t('折百率'),
        dataIndex: 'zbl',
        width: 150,
        align: 'left',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps:{
          disabled:true,
          placeholder:''
        }
      },
      {
        title: t('品次'),
        dataIndex: 'rgrade',
        width: 150,
      },

      // {
      //   title: t('多行文本'),
      //   dataIndex: 'testTextarea',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'InputTextArea',
      //   // 子表自定义验证实例
      //   editRule: (value, _record) => {
      //     return new Promise((resolve, reject) => {
      //       if (!value || value === '') return resolve();
      //       if (value.length < 3) return reject('至少3个字符');
      //       return resolve(); // 验证成功
      //     });
      //   },
      // },
     
    ]);
    posChildTable.setTableData(record.value.mfCarplanFhBList || []);
  }


  async function handSelectgx(selectData, childRecord) {
    console.log(selectData, childRecord);
    posChildTable.updateTableDataRecord(childRecord.id, {
      ...childRecord,
      ...selectData[0],
      ibatch: selectData[0].cbatch,
      cposition: selectData[0].cposCode,
      cposName: selectData[0].cposName,
      // cposition: selectData[0].cposName,
      // editValueRefs:{
      //   ...childRecord.editValueRefs,
      //   zbl:selectData[0].zbl
      // }
    });
  }

  function handleposChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleposChildAdd() {
    posChildTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
      zbl:1
    });
  }

  async function handleposChildDelete(record: Recordable) {
    posChildTable.deleteTableDataRecord(record);
    let arr = await posChildTable.getDataSource();
      let qrzl = 0;
      arr.forEach((item) => {
        qrzl += item.editValueRefs.qrWeight?item.editValueRefs.qrWeight:0;
      });
      setFieldsValue({
        ...getFieldsValue(),
        qrWeight:qrzl,
      });
  }

  async function getposChildList() {
    let posChildListValid = true;
    let posChildList: Recordable[] = [];
    for (const record of posChildTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        posChildListValid = false;
      }
      posChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of posChildTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      posChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!posChildListValid) {
      throw { errorFields: [{ name: ['posChildList'] }] };
    }
    return posChildList;
  }

  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    autoSubmitOnEnter: true,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await mfCarplanFhCForm(data);

    carType.value = res.carType
    record.value = (res.mfCarplanFhC || {}) as CarplanFh;
    setFieldsValue(record.value);
    setposChildTableData(res);
    setDrawerProps({ loading: false });
  });


  const [registerposChildTable, posChildTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleposChildDelete.bind(this, record),
          },
          auth: 'mf:fh:mfCarplanFhH:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });



  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.mfCarplanFhBList = await getposChildList();
      const res = await mfCarplanFhCSaveData(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }


  async function rowChange({ column, value, record:record1 }) {

    // if (column.dataIndex === 'cposition' ) {
      // const { editValueRefs: { cbatch ,qty,zbl,rgrade } } = record1;
      // console.log(1111111111);
      // console.log(obj.value,'obj.value====');
      // zbl.value = obj.value.zbl
      // rgrade.value = obj.value.rgrade
      // cbatch.value = obj.value.cbatch
    // }

    if (column.dataIndex === 'qrWeight' ) {
      const { editValueRefs: { qrWeight ,qty, zbl } } = record1;
      if(carType.value == 1){
        if (value > 0) {
          qrWeight.value = -value;
        }
      }else{
        if (value < 0) {
          qrWeight.value = -value;
        }
      }
      console.log(record1,'record1===');
      let z = zbl.value?zbl.value:1
      qty.value= (qrWeight.value / z).toFixed(4)
      let arr = await posChildTable.getDataSource();
      console.log(arr,'arr=====');
      
      let qrzl = 0;
      arr.forEach((item) => {
        qrzl += item.editValueRefs.qrWeight?item.editValueRefs.qrWeight:0;
      });
      setFieldsValue({
        ...getFieldsValue(),
        qrWeight:qrzl,
      });
    }


    if (column.dataIndex === 'qty' ) {
      const { editValueRefs: { qrWeight ,qty, zbl } } = record1;
      if(carType.value == 1){
        if (value > 0) {
          qty.value = -value;
        }
      }else{
        if (value < 0) {
          qty.value = -value;
        }
      }
      let z = zbl.value?zbl.value:1
      qrWeight.value= qty.value * z

      let arr = await posChildTable.getDataSource();
      let qrzl = 0;
      arr.forEach((item) => {
        qrzl += item.editValueRefs.qrWeight?item.editValueRefs.qrWeight:0;
      });
      setFieldsValue({
        ...getFieldsValue(),
        qrWeight:qrzl,
      });

    }
  }
  function handleEnterKey() {
    handleSubmit();
  }
  
</script>
